#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#include<unistd.h>
#include<sys/stat.h>
#include<dirent.h>
#define N 200

void rm_dir(char *pp)
{
	
	DIR *dir=opendir(pp);
    struct dirent *p=NULL;
			
			   while((p=readdir(dir))!=NULL)
			   {
				    if(strcmp(p->d_name,".")==0||
						strcmp(p->d_name,"..")==0)
					{
					
					continue;
					}
					
					struct stat st;
					char tmp[N]={0};
					strcat(tmp,pp);
					strcat(tmp,"/");
					strcat(tmp,p->d_name);
					lstat(tmp,&st);
					if(S_ISDIR(st.st_mode))
					{
						char tmp[N]={0};
					    strcat(tmp,pp);
						strcat(tmp,"/");
						strcat(tmp,p->d_name);
						
						rm_dir(tmp);
					    continue;
					}
					else
					{
				     char tmp[N]={0};
					   strcat(tmp,pp);
					  tmp[strlen(tmp)]='/';
					  strcat(tmp,p->d_name);
				 
			      
					if(unlink(tmp)==-1)
					{
					printf("FILE %s rm failed\n",p->d_name);
				   	}
			       
				}
			   }
			   
			   closedir(dir);
			   rmdir(pp);
			   

}


int main(int argc,char *argv[])
{
	if(argc==1)
	{
	printf("NO FILE TO RM!\n");
	return 0;
	}
    
	int r_flag=0;
	if(strncmp(argv[1],"-",1)==0)
	{
	   
		if(strcmp(argv[1],"-r")==0)
		{
		  r_flag=1;
		
		}
	     else 
		 {
		 
		 printf("option error\n");
		 return 0;
		 }
	
	}

	if(!r_flag)/////no option
	{
		int i=1;
	  for(;i<argc;i++)
	  {
		  struct stat st;
		  lstat(argv[i],&st);
		  if(S_ISDIR(st.st_mode))
		  {
		  printf("%s is a dir\n",argv[i]);
		  continue;
		  }
	    if(unlink(argv[i])==-1)
		{
		
		printf("\"%s\"rm failed:not exist or .. \n",argv[i]);
		}
	  
	  }
	
	}


	if(r_flag)///have option
	{
	
    	int i=2;
	    for(;i<argc;i++)
     	{
	
		 	 struct stat st;
		 	 lstat(argv[i],&st);
		 	
			 if(S_ISDIR(st.st_mode))
		 	 {
		 	   char tmp[N]={0};
			   getcwd(tmp,N);
			   strcat(tmp,"/");
			   strcat(tmp,argv[i]);
                
			   rm_dir(tmp);
			   continue;

		 	 }
	    
			 if(unlink(argv[i])==-1)
			{
		
			printf("\"%s\"rm failed:not exist or .. \n",argv[i]);
			}
	  
	   }
	
	}
		  
	
	
	
	
	
	
	
return 0;
}
